﻿namespace AddressBook.Business.Person
{
	#region "Using Statements"
	using System;
	using System.Collections.Generic;
	using System.Linq;
	using System.Text;

	using Csla;
	using Csla.Data;
	#endregion

	#region "IAddress Interface"

	public interface IAddress
	{
		String Address1 { get; set; }
		String Address2 { get; set; }
		String City { get; set; }
		Int32 StateProvinceId { get; set; }
		String PostalCode { get; set; }
		String ModifiedDate { get; }
	}

	#endregion

	[Serializable]
	public static class Address
	{
		#region  "Factory Methods"

    #endregion

		#region "Data Access"

		public static Int32 AddAddress(String address1, String address2, String city, Int32 stateProvinceId, String postalCode)
		{
			int addressId;

			using (var ctx = ContextManager<AddressBook.Business.Model.AddressBookDataContext>.GetManager(AddressBook.Business.Model.Database.AddressBook))
			{
				AddressBook.Business.Model.Address address = new AddressBook.Business.Model.Address();

				address.AddressLine1 = address1;
				address.AddressLine2 = address2;
				address.City = city;
				address.StateProvinceId = stateProvinceId;
				address.PostalCode = postalCode;
				address.ModifiedDate = System.DateTime.Now;

				ctx.DataContext.Addresses.InsertOnSubmit(address);
				ctx.DataContext.SubmitChanges();

				addressId = address.Id;
			}

			return addressId;
		}

		public static void UpdateAddress(Int32 addressId, String address1, String address2, String city, Int32 stateProvinceId, String postalCode)
		{
			using (var ctx = ContextManager<AddressBook.Business.Model.AddressBookDataContext>.GetManager(AddressBook.Business.Model.Database.AddressBook))
			{
				AddressBook.Business.Model.Address address = ctx.DataContext.Addresses.First(a => a.Id == addressId);

				address.AddressLine1 = address1;
				address.AddressLine2 = address2;
				address.City = city;
				address.StateProvinceId = stateProvinceId;
				address.PostalCode = postalCode;
				address.ModifiedDate = System.DateTime.Now;

				ctx.DataContext.SubmitChanges();
			}
		}

		public static void RemoveAddress(Int32 addressId)
		{
			using (var ctx = ContextManager<AddressBook.Business.Model.AddressBookDataContext>.GetManager(AddressBook.Business.Model.Database.AddressBook))
			{
				AddressBook.Business.Model.Address address = ctx.DataContext.Addresses.First(a => a.Id == addressId);

				// delete address data
				ctx.DataContext.Addresses.DeleteOnSubmit(address);
				ctx.DataContext.SubmitChanges();
			}
		}

		#endregion
	}
}
